import { colorTools } from './colorTools';

/**
 * 视频处理工具类
 */
export const videoProcessor = {
  /**
   * 处理当前帧
   * @param {Object} options 处理选项
   * @param {HTMLVideoElement} options.video 视频元素
   * @param {HTMLCanvasElement} options.canvas 画布元素
   * @param {CanvasRenderingContext2D} options.ctx 画布上下文
   * @param {Object} options.cropParams 裁剪参数
   * @param {boolean} options.enableTransparency 是否启用透明处理
   * @param {Array} options.targetColor 目标颜色RGB数组
   * @param {number} options.threshold 阈值
   */
  processCurrentFrame({ video, canvas, ctx, cropParams, enableTransparency, targetColor, threshold }) {
    // 获取截图参数并验证
    const validCropParams = {
      left: Math.max(0, parseInt(cropParams.left || 0)),
      top: Math.max(0, parseInt(cropParams.top || 0)),
      width: Math.min(video.videoWidth, parseInt(cropParams.width || 100)),
      height: Math.min(video.videoHeight, parseInt(cropParams.height || 100))
    };

    // 调整画布尺寸
    canvas.width = validCropParams.width;
    canvas.height = validCropParams.height;

    // 执行区域截图
    ctx.drawImage(
      video,
      validCropParams.left, validCropParams.top,   // 源起点
      validCropParams.width, validCropParams.height, // 源尺寸
      0, 0,                              // 目标起点
      validCropParams.width, validCropParams.height  // 目标尺寸
    );

    // 如果启用了透明处理，则进行颜色匹配和透明化
    if (enableTransparency) {
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const processedData = colorTools.applyTransparency(imageData, targetColor, threshold);
      ctx.putImageData(processedData, 0, 0);
    }

    return canvas;
  },

  /**
   * 开始处理视频
   * @param {Object} options 处理选项
   */
  async startVideoProcessing({
    videoFile, sourceVideo, canvas, ctx, initCanvas, cropParams,
    frameInterval, enableTransparency, targetColor, colorThreshold,
    startTime = 0, endTime = 0,  // 添加时间范围参数
    onProgress, onComplete
  }) {
    if (!sourceVideo) throw new Error('视频元素不存在');

    sourceVideo.src = URL.createObjectURL(videoFile);
    
    await new Promise((resolve, reject) => {
      sourceVideo.onloadedmetadata = resolve;
      sourceVideo.onerror = () => reject(new Error('视频加载失败'));
    });

    // 初始化画布
    if (!canvas || !ctx) {
      initCanvas();
      if (!canvas || !ctx) throw new Error('无法创建画布');
    }

    canvas.width = sourceVideo.videoWidth;
    canvas.height = sourceVideo.videoHeight;

    // 初始化时间轴
    // 设置起始时间
    console.log(`处理视频时间范围: ${startTime}s - ${endTime}s`);
    const actualStartTime = Math.max(0, startTime || 0);
    const actualEndTime = endTime > 0 ? Math.min(endTime, sourceVideo.duration) : sourceVideo.duration;
    
    sourceVideo.currentTime = actualStartTime;
    const frames = [];
    let frameCounter = 0;
    onProgress(0, 0, "开始处理视频帧...");
    
    const frameDuration = 1 / 30;
    const interval = Math.max(1, parseInt(frameInterval) || 1);

    while (sourceVideo.currentTime < actualEndTime) {
      frameCounter++;
      if (frameCounter % interval !== 0) {
        sourceVideo.currentTime = Math.min(sourceVideo.currentTime + frameDuration, sourceVideo.duration);
        continue;
      }

      await new Promise(resolve => {
        sourceVideo.onseeked = () => {
          try {
            // 处理当前帧
            this.processCurrentFrame({
              video: sourceVideo,
              canvas,
              ctx,
              cropParams,
              enableTransparency,
              targetColor,
              threshold: colorThreshold
            });
            
            // 保存帧
            const frameDataURL = canvas.toDataURL('image/png');
            onProgress(
              (sourceVideo.currentTime / sourceVideo.duration * 100),
              sourceVideo.currentTime,
              `已处理 ${frames.length} 帧...`,
              frameDataURL
            );
            
            resolve();
          } catch (error) {
            console.error('处理帧时出错:', error);
            resolve();
          }
        };
        sourceVideo.currentTime = Math.min(sourceVideo.currentTime + frameDuration, sourceVideo.duration);
      });

      if (frames.length % 50 === 0) {
        await new Promise(r => setTimeout(r, 0));
      }
    }
    
    onComplete();
  }
};